'''
Created on Jan 25, 2010

@author: madsk
'''

from PyQt4 import QtCore
from task import Task

class ThreadPool(QtCore.QThreadPool):
    taskStarted = QtCore.pyqtSignal(int)
    taskProgress = QtCore.pyqtSignal(int, float, str)
    taskFinished = QtCore.pyqtSignal(int, int)
    
    def __init__(self, app, parent=None):
        super(ThreadPool, self).__init__(parent)
        self._app = app
        self._activetasks = {}
        
        self.setMaxThreadCount(4)
    
    def performTask(self, image_path, operations):        
        # Launch the task in the threadpool.
        task = Task(image_path, operations)
        self._activetasks[task.id] = (image_path, task)
        task.started.connect(self._handleTaskStarted)
        task.finished.connect(self._handleTaskFinished)
        task.progress.connect(self._handleTaskProgress)
        self.start(task)
        
    def _handleTaskStarted(self, taskid):
        self.taskStarted.emit(taskid)
    
    def _handleTaskFinished(self, taskid, rcode):
        self.taskFinished.emit(taskid, rcode)
        self._activetasks.pop(taskid)
        if rcode == 0:
            self._app.popup_message('Task %i finished.'%taskid)
        else:
            self._app.popup_message('Task %i failed. Error code = %i'%(taskid, rcode))
        
    def _handleTaskProgress(self, taskid, progress, comment):
        self.taskProgress.emit(taskid, progress, comment)